import { createActions, handleActions } from 'redux-actions';
import createNoEffect from '@redux/create-no-effect';
import { getNotifyList } from '@api/notify';
import { get } from 'lodash';

const initState = {
  loadNoticeStatus: 'notStart',
  noticeCount: 0
};

const noEffects = createNoEffect(['SET_LOAD_NOTICE_STATUS']);

export const actions = createActions({
  LOAD_NOTICE: () => dispatch => {
    dispatch(actions.setLoadNoticeStatus('pending'));
    return getNotifyList({ read: 'false' })
      .then(res => {
        dispatch(actions.setLoadNoticeStatus('succeed'));
        return Promise.resolve(res);
      })
      .catch(error => {
        dispatch(actions.setLoadNoticeStatus('failed'));
        return Promise.reject(error);
      })
      .finally(() => {
        dispatch(actions.setLoadNoticeStatus('notStart'));
      });
  },
  ...noEffects.actions
});

const reducer = handleActions(
  {
    LOAD_NOTICE: (state, action) => {
      const { error, payload } = action;
      if (error) {
        return state;
      }
      const noticeCount = get(payload, 'data.data.count', 0);
      return {
        ...state,
        noticeCount
      };
    },
    ...noEffects.reducers
  },
  initState
);

export default reducer;
